const Koa = require('koa')
const Router = require('@koa/router')
const ExcelJS = require('exceljs')
const fs = require('fs')
const crypto = require('crypto')
const _ = require('lodash')
const generateDocx = require('./docxtemplater')

const app = new Koa()
const router = new Router({ prefix: '/api' })


const getMD5 = (content) => crypto.createHash('md5').update(content).digest("hex")

//匹配模板文档里的{变量}
const excel_value_reg = /{(\w+)}/g

//对输入参数进行排序
function sortquerystring(arr) {
  let str = ''
  Object.keys(arr).sort().forEach(key => {
    str += (key + '=' + arr[key] + '&')
  })
  return _.trimEnd(str, '&')
}

router.get('/', async (ctx, next) => {
  ctx.body = ''
})

router.get('/xlsx/:file_name', async (ctx, next) => {
  const { file_name } = ctx.params
  const file_full_name = 'xlsx/' + file_name + '.xlsx'
  if (!fs.existsSync(file_full_name)) {
    ctx.body = { code: -102, msg: '模板不存在' }
    return
  }
  const new_file_name = 'temp/' + getMD5(file_name + sortquerystring(ctx.query)) + '.xlsx'
  if (!fs.existsSync(new_file_name)) {
    const data = ctx.query
    const workbook = new ExcelJS.Workbook()
    await workbook.xlsx.readFile(file_full_name)
    const worksheet = workbook.getWorksheet(1);
    worksheet.eachRow(function (row, rowNumber) {
      row.eachCell(function (cell, colNumber) {
        const r = excel_value_reg.exec(cell.value)
        if (r) {
          const value = data[r[1]] || ''
          cell.value = cell.value.replace(excel_value_reg, value)
        }
      })
    })
    await workbook.xlsx.writeFile(new_file_name)
  }
  ctx.body = { code: 0, data: new_file_name }
})

router.get('/docx/:file_name', async (ctx, next) => {
  const { file_name } = ctx.params
  const file_full_name = 'docx/' + file_name + '.docx'
  if (!fs.existsSync(file_full_name)) {
    ctx.body = { code: -102, msg: '模板不存在' }
    return
  }
  const new_file_name = 'temp/' + getMD5(file_name + sortquerystring(ctx.query)) + '.docx'
  if (!fs.existsSync(new_file_name)) {
    const data = ctx.query
    const result = generateDocx(file_full_name, data, new_file_name)
    if (!result) {
      ctx.body = { code: -100, msg: '获取失败' }
      return
    }
  }
  ctx.body = { code: 0, data: new_file_name }
})



app.use(async (ctx, next) => {
  ctx.set('Access-Control-Allow-Origin', '*')//支持跨域请求
  await next();
})
app.use(router.routes())//注册路由
app.listen(3601, () => console.log('服务已启动,浏览器打开访问 localhost:3601'))